//
//  SaoMaViewController.m
//  Test
//
//  Created by jingyao on 2018/1/4.
//  Copyright © 2018年 jingyao. All rights reserved.
//

#import "SaoMaViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PlantViewController.h"
#import "Global.h"

@interface SaoMaViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate, CAAnimationDelegate>

@property (strong, nonatomic)UIImageView *imgView;
@property (strong, nonatomic)AVCaptureDevice *device;//以下都是扫码要用的
@property (strong, nonatomic)AVCaptureDeviceInput *input;
@property (strong, nonatomic)AVCaptureMetadataOutput *output;
@property (strong, nonatomic)AVCaptureSession *session;
@property (strong, nonatomic)AVCaptureVideoPreviewLayer *preview;

@property (assign, nonatomic)Boolean isntFirst1;//用于判断初始化方法是不是第一次执行
@property (assign, nonatomic)Boolean isntFirst2;

@end

@implementation SaoMaViewController

#pragma mark - 生命周期方法,内部方法调用顺序必须这么写，否则有各种问题

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    //设置横线图片和平移动画,不放这里不动
    [self setupImageAnimation];
    
    //透明遮罩层初始化
    [self addTransparentLayer];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view layoutIfNeeded];
    
    //扫码初始化
    [self scanCode];
}

#pragma mark - 初始化方法

//添加遮罩层
- (void)addTransparentLayer {
    if (self.isntFirst1) {
        return;
    }else {
        CAShapeLayer *transparentLayer = [[CAShapeLayer alloc] init];
        transparentLayer.frame = self.view.frame;
        transparentLayer.fillColor = [UIColor colorWithWhite:0.0f alpha:0.5f].CGColor;
        [self.view.layer addSublayer:transparentLayer];
        
        UIBezierPath *path1 = [UIBezierPath bezierPathWithRect:transparentLayer.bounds];
        UIBezierPath *path2 = [[UIBezierPath bezierPathWithRect:self.scanBgImgView.frame] bezierPathByReversingPath];//path是画线条，append是取交集，交集的区域能赋值给cashapelayer的path属性
        [path1 appendPath:path2];
        transparentLayer.path = path1.CGPath;
        
        self.isntFirst1 = YES;
    }
}

- (void)setupImageAnimation {
    self.imgView = [[UIImageView alloc] init];
    self.imgView.image = [UIImage imageNamed:@"scan_img_code2"];
    [self.view addSubview:self.imgView];
    [self.imgView setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.imgView attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scanBgImgView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.imgView attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scanBgImgView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.imgView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]];
    [self.imgView addConstraint:[NSLayoutConstraint constraintWithItem:self.imgView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:20.0f]];
    
    [self.view layoutIfNeeded];//重新获取位置
    
    CGFloat xFromPosition = self.imgView.layer.position.x;
    CGFloat yFromPosition = self.imgView.layer.position.y;
    
    CGFloat xToPosition = xFromPosition;
    CGFloat yToPosition = yFromPosition + self.scanBgImgView.layer.frame.size.height - self.imgView.layer.frame.size.height;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.duration = 3.5;//动画持续时间
    animation.repeatCount = NSIntegerMax;//无限重复
    animation.beginTime = CACurrentMediaTime();//立刻开始执行动画
    animation.autoreverses = YES;//结束后执行逆转动画
    animation.fromValue = [NSValue valueWithCGPoint:self.imgView.layer.position];//动画起始位置
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(xToPosition, yToPosition)];//动画的终止位置
    animation.delegate = self;
    [self.imgView.layer addAnimation:animation forKey:@"key"];//为layer添加设置完成的动画
    if (self.isntFirst2) {
        return;
    }else {
        self.imgView = [[UIImageView alloc] init];
        self.imgView.image = [UIImage imageNamed:@"scan_img_code2"];
        [self.view addSubview:self.imgView];
        [self.imgView setTranslatesAutoresizingMaskIntoConstraints:NO];
        
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.imgView attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scanBgImgView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.imgView attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f]];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.scanBgImgView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.imgView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f]];
        [self.imgView addConstraint:[NSLayoutConstraint constraintWithItem:self.imgView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:20.0f]];
        
        [self.view layoutIfNeeded];//重新获取位置
        
        CGFloat xFromPosition = self.imgView.layer.position.x;
        CGFloat yFromPosition = self.imgView.layer.position.y;
        
        CGFloat xToPosition = xFromPosition;
        CGFloat yToPosition = yFromPosition + self.scanBgImgView.layer.frame.size.height - self.imgView.layer.frame.size.height;
        
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
        animation.delegate = self;//添加代理方法
        animation.duration = 3.5;//动画持续时间
        animation.repeatCount = 1;//重复一次
        animation.beginTime = CACurrentMediaTime();//立刻开始执行动画
        animation.autoreverses = YES;//结束后执行逆转动画
        animation.fromValue = [NSValue valueWithCGPoint:self.imgView.layer.position];//动画起始位置
        animation.toValue = [NSValue valueWithCGPoint:CGPointMake(xToPosition, yToPosition)];//动画的终止位置
        
        [self.imgView.layer addAnimation:animation forKey:@"key"];//为layer添加设置完成的动画
        
        self.isntFirst2 = YES;
    }
}

#pragma mark - 扫码需要用到的方法o

- (void)scanCode {
    //扫码要用到的初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    self.output = [[AVCaptureMetadataOutput alloc]init];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    self.session = [[AVCaptureSession alloc] init];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];//扫描频率高
    
    //连接输入和输出
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    //设置条码类型
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    //添加扫描画面
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.preview.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    //开始扫描
    [self.session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    NSString *stringValue;
    if (metadataObjects.count >0){
        NSLog(@"进入了didOutputMetadataObjects代理方法中");
        //停止扫描
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        NSLog(@"stringValue是：%@", stringValue);
        
        [self jumpToPageAccordingToValue:stringValue];
    }
}

#pragma mark - 点击事件

- (IBAction)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)photoAlbumAction:(id)sender {
    [self openLocalPhoto];
}

#pragma mark - 本地相册识别二维码

- (void)openLocalPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = YES;//设置选择后的图片可被编辑
    [self presentViewController:picker animated: YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])  {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        [self tellQRCodeWithImage:image];
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"您取消了选择图片");
    [self dismissViewControllerAnimated: YES completion: nil];
}

#pragma mark - 通过传入图片识别其中的二维码

- (void)tellQRCodeWithImage:(UIImage *)image {
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    for (int index = 0; index < [features count]; index ++) {
        CIQRCodeFeature *feature = [features objectAtIndex:index];
        NSString *scannedResult = feature.messageString;
        NSLog(@"识别二维码结果是result:%@",scannedResult);
    }
}


#pragma mark - caanimationdelegate方法

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    CGFloat xFromPosition = self.imgView.layer.position.x;
    CGFloat yFromPosition = self.imgView.layer.position.y;
    
    CGFloat xToPosition = xFromPosition;
    CGFloat yToPosition = yFromPosition + self.scanBgImgView.layer.frame.size.height - self.imgView.layer.frame.size.height;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.delegate = self;//添加代理方法
    animation.duration = 3.5;//动画持续时间
    animation.repeatCount = 1;//重复一次
    animation.beginTime = CACurrentMediaTime();//立刻开始执行动画
    animation.autoreverses = YES;//结束后执行逆转动画
    animation.fromValue = [NSValue valueWithCGPoint:self.imgView.layer.position];//动画起始位置
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(xToPosition, yToPosition)];//动画的终止位置
    
    [self.imgView.layer addAnimation:animation forKey:@"key"];//为layer添加设置完成的动画
}

#pragma mark - 根据扫码结果判断跳转页面

- (void)jumpToPageAccordingToValue:(NSString *)value {
    PlantViewController *plantVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"plantVC"];
    
    if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant01.htm"]) {
        //陰香
    }else if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant02.htm"]) {
        //粉紅油茶
    }else if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant03.htm"]) {
        //人面子
    }else if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant04.htm"]) {
        //桂花
    }else if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant05.htm"]) {
        //細葉欖仁
    }else if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant06.htm"]) {
        //秋楓
    }else if ([value isEqualToString:@"http://www.18kingwahroad.com.hk/smartapp/plant07.htm"]) {
        //鳳凰木
    }
}
@end
